<template>
  <div class="product-form-container">
    <div class="form-header">
      <h2 class="form-title">{{ isEdit ? '编辑商品' : '创建商品' }}</h2>
      <button class="close-btn" @click="$emit('close')">
        <i class="icon-close"></i>
      </button>
    </div>
    
    <div class="form-body">
      <form @submit.prevent="submitForm">
        <!-- 商品名称 -->
        <div class="form-group">
          <label for="name" class="form-label required">商品名称</label>
          <input 
            id="name"
            v-model="formData.name"
            type="text"
            class="form-input"
            placeholder="请输入商品名称"
            required
          />
          <div v-if="errors.name" class="error-message">{{ errors.name }}</div>
        </div>
        
        <!-- 商品价格 -->
        <div class="form-group">
          <label for="price" class="form-label required">商品价格</label>
          <div class="input-with-prefix">
            <span class="input-prefix">¥</span>
            <input 
              id="price"
              v-model="formData.price"
              type="number"
              step="0.01"
              min="0.01"
              class="form-input with-prefix"
              placeholder="请输入商品价格"
              required
            />
          </div>
          <div v-if="errors.price" class="error-message">{{ errors.price }}</div>
        </div>
        
        <!-- 商品分类 -->
        <div class="form-group">
          <label for="categoryId" class="form-label required">商品分类</label>
          <select 
            id="categoryId"
            v-model="formData.categoryId"
            class="form-select"
            required
          >
            <option value="" disabled>请选择商品分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
          <div v-if="errors.categoryId" class="error-message">{{ errors.categoryId }}</div>
        </div>
        
        <!-- 商品库存 -->
        <div class="form-group">
          <label for="totalStock" class="form-label required">商品库存</label>
          <input 
            id="totalStock"
            v-model="formData.totalStock"
            type="number"
            min="0"
            class="form-input"
            placeholder="请输入商品库存"
            required
          />
          <div v-if="errors.totalStock" class="error-message">{{ errors.totalStock }}</div>
        </div>
        
        <!-- 安全库存 -->
        <div class="form-group">
          <label for="safeStock" class="form-label required">安全库存</label>
          <input 
            id="safeStock"
            v-model="formData.safeStock"
            type="number"
            min="0"
            class="form-input"
            placeholder="请输入安全库存"
            required
          />
          <div class="form-hint">当库存低于安全库存时，系统将发出预警</div>
          <div v-if="errors.safeStock" class="error-message">{{ errors.safeStock }}</div>
        </div>
        
        <!-- 商品状态 -->
        <div class="form-group" v-if="isEdit">
          <label class="form-label">商品状态</label>
          <div class="status-toggle">
            <span class="status-label">下架</span>
            <label class="switch">
              <input type="checkbox" v-model="isActive">
              <span class="slider round"></span>
            </label>
            <span class="status-label">上架</span>
          </div>
        </div>
        
        <!-- 商品图片 -->
        <div class="form-group">
          <label class="form-label">商品图片</label>
          <div class="image-upload-container">
            <div 
              class="image-preview" 
              v-if="formData.mainImageUrl" 
              :style="{ backgroundImage: `url(${formData.mainImageUrl})` }"
            >
              <button type="button" class="remove-image-btn" @click="removeImage">
                <i class="icon-trash"></i>
              </button>
            </div>
            <div v-else class="upload-placeholder" @click="selectImage">
              <i class="icon-image"></i>
              <span>点击上传图片</span>
            </div>
          </div>
          <div v-if="errors.mainImageUrl" class="error-message">{{ errors.mainImageUrl }}</div>
        </div>
        
        <!-- 商品描述 -->
        <div class="form-group">
          <label for="description" class="form-label">商品描述</label>
          <textarea 
            id="description"
            v-model="formData.description"
            class="form-textarea"
            placeholder="请输入商品描述"
            rows="4"
          ></textarea>
          <div v-if="errors.description" class="error-message">{{ errors.description }}</div>
        </div>
        
        <!-- 商家ID (隐藏字段，通常由系统自动设置) -->
        <input type="hidden" v-model="formData.merchantId">
        
        <!-- 表单按钮 -->
        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="$emit('close')">取消</button>
          <button type="submit" class="btn-submit" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : (isEdit ? '保存修改' : '创建商品') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProductForm',
  props: {
    product: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        id: null,
        name: '',
        description: '',
        price: '',
        categoryId: '',
        totalStock: '',
        safeStock: '',
        status: 1,
        mainImageUrl: '',
        merchantId: 1 // 默认商家ID，实际应从用户信息中获取
      },
      isActive: true,
      isSubmitting: false,
      errors: {},
      categories: [
        { id: 1, name: '生活用品' },
        { id: 2, name: '零食' },
        { id: 3, name: '饮料' },
        { id: 4, name: '食品' },
        { id: 6, name: '个人护理' },
        { id: 7, name: '清洁用品' },
        { id: 8, name: '口腔护理' },
        { id: 10, name: '电子配件' },
        { id: 11, name: '电脑配件' }
      ]
    };
  },
  watch: {
    isActive(val) {
      this.formData.status = val ? 1 : 0;
    }
  },
  created() {
    if (this.isEdit && this.product) {
      // 编辑模式，填充表单数据
      this.formData = { ...this.product };
      this.isActive = this.formData.status === 1;
    }
  },
  methods: {
    validateForm() {
      this.errors = {};
      let isValid = true;
      
      // 商品名称验证
      if (!this.formData.name.trim()) {
        this.errors.name = '商品名称不能为空';
        isValid = false;
      } else if (this.formData.name.length > 100) {
        this.errors.name = '商品名称不能超过100个字符';
        isValid = false;
      }
      
      // 价格验证
      if (!this.formData.price) {
        this.errors.price = '商品价格不能为空';
        isValid = false;
      } else {
        const price = parseFloat(this.formData.price);
        if (isNaN(price) || price <= 0) {
          this.errors.price = '商品价格必须大于0';
          isValid = false;
        }
      }
      
      // 分类验证
      if (!this.formData.categoryId) {
        this.errors.categoryId = '请选择商品分类';
        isValid = false;
      }
      
      // 库存验证
      if (this.formData.totalStock === '') {
        this.errors.totalStock = '商品库存不能为空';
        isValid = false;
      } else {
        const totalStock = parseInt(this.formData.totalStock);
        if (isNaN(totalStock) || totalStock < 0) {
          this.errors.totalStock = '商品库存不能为负数';
          isValid = false;
        }
      }
      
      // 安全库存验证
      if (this.formData.safeStock === '') {
        this.errors.safeStock = '安全库存不能为空';
        isValid = false;
      } else {
        const safeStock = parseInt(this.formData.safeStock);
        if (isNaN(safeStock) || safeStock < 0) {
          this.errors.safeStock = '安全库存不能为负数';
          isValid = false;
        }
      }
      
      return isValid;
    },
    
    async submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      this.isSubmitting = true;
      
      try {
        // 准备提交的数据
        const productData = {
          ...this.formData,
          price: parseFloat(this.formData.price),
          totalStock: parseInt(this.formData.totalStock),
          safeStock: parseInt(this.formData.safeStock)
        };
        
        let response;
        
        if (this.isEdit) {
          // 更新商品
          response = await this.updateProduct(productData);
        } else {
          // 创建商品
          response = await this.createProduct(productData);
        }
        
        if (response.code === 200) {
          this.$emit('success', response.data);
          this.$emit('close');
          
          // 显示成功提示
          uni.showToast({
            title: this.isEdit ? '商品更新成功' : '商品创建成功',
            icon: 'success'
          });
        } else {
          // 显示错误提示
          uni.showToast({
            title: response.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交商品表单失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.isSubmitting = false;
      }
    },
    
    async createProduct(productData) {
      const response = await uni.request({
        url: '/api/products',
        method: 'POST',
        data: productData,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        }
      });
      
      return response.data;
    },
    
    async updateProduct(productData) {
      const response = await uni.request({
        url: `/api/products/${productData.id}`,
        method: 'PUT',
        data: productData,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        }
      });
      
      return response.data;
    },
    
    getToken() {
      // 从存储中获取token
      try {
        return uni.getStorageSync('token') || '';
      } catch (e) {
        console.error('获取token失败:', e);
        return '';
      }
    },
    
    selectImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 这里应该上传图片到服务器，获取URL
          // 为了演示，我们直接使用本地临时路径
          this.uploadImage(res.tempFilePaths[0]);
        }
      });
    },
    
    async uploadImage(filePath) {
      uni.showLoading({
        title: '上传中...'
      });
      
      try {
        // 模拟上传图片到服务器
        // 实际应用中，应该调用上传API
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 假设服务器返回了图片URL
        this.formData.mainImageUrl = filePath;
        
        uni.hideLoading();
      } catch (error) {
        console.error('上传图片失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '上传图片失败',
          icon: 'none'
        });
      }
    },
    
    removeImage() {
      this.formData.mainImageUrl = '';
    }
  }
}
</script>

<style scoped>
.product-form-container {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eaeaea;
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
}

.form-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.required:after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.input-with-prefix {
  position: relative;
  display: flex;
  align-items: center;
}

.input-prefix {
  position: absolute;
  left: 12px;
  color: #999;
}

.form-input.with-prefix {
  padding-left: 24px;
}

.form-hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.status-toggle {
  display: flex;
  align-items: center;
}

.status-label {
  margin: 0 8px;
  font-size: 14px;
  color: #666;
}

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  transition: .4s;
}

input:checked + .slider {
  background-color: #1890ff;
}

input:focus + .slider {
  box-shadow: 0 0 1px #1890ff;
}

input:checked + .slider:before {
  transform: translateX(20px);
}

.slider.round {
  border-radius: 20px;
}

.slider.round:before {
  border-radius: 50%;
}

.image-upload-container {
  margin-top: 8px;
}

.image-preview {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.remove-image-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-placeholder {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: #1890ff;
}

.upload-placeholder i {
  font-size: 24px;
  color: #999;
  margin-bottom: 8px;
}

.upload-placeholder span {
  font-size: 12px;
  color: #999;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.btn-cancel {
  padding: 8px 16px;
  background: none;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
  margin-right: 12px;
  cursor: pointer;
}

.btn-submit {
  padding: 8px 16px;
  background-color: #1890ff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  color: white;
  cursor: pointer;
}

.btn-submit:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}

/* 图标样式 */
.icon-close:before {
  content: "×";
}

.icon-trash:before {
  content: "🗑";
}

.icon-image:before {
  content: "🖼";
}
</style>
